import os
import subprocess
import json
import datetime

# 配置不活跃的时间阈值，例如30天
INACTIVE_THRESHOLD_DAYS = 30

def get_deployments():
    result = subprocess.run(['kubectl', 'get', 'deployments', '-n', 'current-semester'], capture_output=True, text=True)
    deployments = str(result).split(f'\\n')[1:-1]
    
    return deployments['items']

def get_last_active_time(deployment):
    last_active_time = deployment['metadata']['annotations'].get('kubectl.kubernetes.io/last-applied-configuration')
    if last_active_time:
        last_active_time = json.loads(last_active_time).get('metadata', {}).get('creationTimestamp')
    return last_active_time

def is_inactive(last_active_time):
    if not last_active_time:
        return False
    last_active_time = datetime.datetime.strptime(last_active_time, '%Y-%m-%dT%H:%M:%SZ')
    current_time = datetime.datetime.utcnow()
    return (current_time - last_active_time).days > INACTIVE_THRESHOLD_DAYS

def scale_down_deployment(name, namespace):
    subprocess.run(['kubectl', 'scale', '--replicas=0', 'deployment', name, '-n', namespace])

def main():
    deployments = get_deployments()
    
    for deployment in deployments:
        name = deployment['metadata']['name']
        namespace = deployment['metadata']['namespace']
        namespace = 'current-semester'
        last_active_time = get_last_active_time(deployment)
        if is_inactive(last_active_time):
            print(f"Scaling down inactive deployment: {name} in namespace {namespace}")
            # scale_down_deployment(name, namespace)

if __name__ == "__main__":
    main()
